//
//  UIControl+TouchLimit.m
//  YHKit
//
//  Created by lin on 2020/8/12.
//  Copyright © 2020 000. All rights reserved.
//

#import "UIControl+TouchLimit.h"
#import <objc/runtime.h>
#import <YHConstant/YHConstant+Method.h>
#import "NSDate+YH.h"

/// 默认的事件间隔
CGFloat const YHLimitDefaultTimeInterval = 0.3;

@implementation UIControl (TouchLimit)

-(NSTimeInterval)limitTimeInterval{
    id timeInterval = objc_getAssociatedObject(self,@selector(limitTimeInterval));
    if(timeInterval){
        return [timeInterval doubleValue];
    }
    [self setLimitTimeInterval:YHLimitDefaultTimeInterval];
    return YHLimitDefaultTimeInterval;
}
-(void)setLimitTimeInterval:(NSTimeInterval)limitTimeInterval{
    objc_setAssociatedObject(self,@selector(limitTimeInterval),@(limitTimeInterval),OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

/// 最后一次发起点击事件的事件
-(NSTimeInterval)lastTouchEventTimeInterval{
    return [objc_getAssociatedObject(self,@selector(lastTouchEventTimeInterval)) doubleValue];
}
-(void)setLastTouchEventTimeInterval:(NSTimeInterval)lastTouchEventTimeInterval{
    objc_setAssociatedObject(self,@selector(lastTouchEventTimeInterval),@(lastTouchEventTimeInterval),OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(BOOL)isNoLimit{
    return [objc_getAssociatedObject(self,@selector(isNoLimit)) boolValue];
}
-(void)setIsNoLimit:(BOOL)isNoLimit{
    objc_setAssociatedObject(self,@selector(isNoLimit),@(isNoLimit),OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(void (^)(void))limitRepeatBlock{
    return objc_getAssociatedObject(self, @selector(limitRepeatBlock));
}
-(void)setLimitRepeatBlock:(void (^)(void))limitRepeatBlock{
    objc_setAssociatedObject(self, @selector(limitRepeatBlock), limitRepeatBlock, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

+ (void)load {
    yh_swizzleMethod(self, @selector(sendAction:to:forEvent:), @selector(limitSendAction:to:forEvent:));
    
}

- (void)limitSendAction:(SEL)action to:(id)target forEvent:(UIEvent*)event{
    
    UITouch * touch = [[event allTouches] anyObject];
    if(self.isNoLimit ||
       ![self isKindOfClass:[UIButton class]] ||
       touch.phase != UITouchPhaseEnded){
        [self limitSendAction:action to:target forEvent:event];
        return;
    }
    NSTimeInterval nowTimestamp = [NSDate yh_timestamp];
    NSTimeInterval mistiming = nowTimestamp - self.lastTouchEventTimeInterval;

    if(mistiming > self.limitTimeInterval){
        //超过这个时间间隔 可以点击
        self.lastTouchEventTimeInterval = nowTimestamp;
        
        //延迟一下 展示一下点击效果
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self limitSendAction:action to:target forEvent:event];
        });
        return;
    }
    
    //在这个间隔内不能重复点击
    if(self.limitRepeatBlock){
        self.limitRepeatBlock();
    }
}

@end
